package org.reenscape;
import java.net.*;
import java.io.*;

import org.reenscape.lib.Print;
import org.reenscape.lib.Configuration;
/**
* Controls listener that accepts new connections and makes new Players.
@author Jim
@version 2.2
*/
public class ClientAccepter implements Runnable {

	/**
	* Runs the accept loop and adds new players.
	*/
		public void run() {
		try {
			CloseListener = false;
			listener = new ServerSocket(Configuration.basePort, 1, null);
			Print.println("[CON] Server has been bound to port "+listener.getLocalPort()+".");			
			while(true) {
				Socket s = listener.accept();
				s.setTcpNoDelay(true);
				String connectingHost = s.getInetAddress().getHostName();
				if(true) {
					if (Blacklisted(connectingHost)) {
						//IP is blacklisted for sending null logins.
						s.close();
					} else {
						int Found = -1;
						for (int i = 0; i < MaxConnections; i++) {
							if (Connections[i] == connectingHost) {
								Found = ConnectionCount[i];
								break;
							}
						}
						if (Found < 3) {
							Print.println("[CON] Accepting connection from "+connectingHost+".");
							Server.clientUpdater.newPlayerClient(s, connectingHost);
						} else {
							s.close();
						}
					}
				} else {
					Print.println("[CON] Rejecting connection from "+connectingHost+".");
					s.close();
				}
			}
		} catch(java.io.IOException ioe) {
			if(!CloseListener) {
				Print.notice("[CON] Unable to start up listener on "+Configuration.basePort, "Error");
			} else {
				Print.notice("[CON] ClientHandler was shut down.", "System Warning");
			}
		}
	}

	/**
	* Shuts down the socket listener.
	*/
	public void kill() {
		try {
			CloseListener = true;
			if(listener != null) listener.close();
			listener = null;
		} catch(java.lang.Exception er) {}
	}
	
	/**
	* Checks if IP is blacklisted.
	*/
	public boolean Blacklisted(String testString) {
		try {
			BufferedReader in = new BufferedReader(new FileReader("../local/blacklist.txt"));
			String data = null;
			while((data = in.readLine()) != null) {
				if(testString.equalsIgnoreCase(data)) {
					return true;
				}
			}
		} catch(IOException e) {

		}
	return false;
	}
	
	/**
	* Socket used to accept connections.
	*/
	public static ServerSocket listener = null;
	
	/**
	* Max amount of connections.
	*/
	public static int MaxConnections = 100000;
	
	/**
	* Array of all of the hosts of the incoming connections.
	*/
	public static String[] Connections = new String[MaxConnections];
	
	/**
	* Array of the number of current connections.
	*/
	public static int[] ConnectionCount = new int[MaxConnections];
	
	/**
	* Shut down the listener.
	*/
	public static boolean CloseListener;
}